from django.shortcuts import render

# Create your views here.
from django.views.generic import View
from rest_framework import status

from book.models import BookInfo
from django.http import JsonResponse
import json

# Create your views here.
from book.serializers import BookInfoModelSerializer


class BookListView(View):
    """
    查询所有图书、增加图书
    """
    def get(self, request):
        """
        查询所有图书
        路由：GET /books/
        """
        queryset = BookInfo.objects.all()
        book_list = []
        for book in queryset:
            book_list.append({
                'id': book.id,
                'name': book.name,
                'pub_date': book.pub_date
            })
        return JsonResponse(book_list, safe=False)

    def post(self, request):
        """
        新增图书
        路由：POST /books/
        """
        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book = BookInfo.objects.create(
            name=book_dict.get('name'),
            pub_date=book_dict.get('pub_date')
        )

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        },safe=False)

class BookDetailView(View):
    """
    获取单个图书信息
    修改图书信息
    删除图书
    """
    def get(self, request, pk):
        """
        获取单个图书信息
        路由： GET  /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({},status=404)

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        })

    def put(self, request, pk):
        """
        修改图书信息
        路由： PUT  /books/<pk>
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({},status=404)

        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book.name = book_dict.get('name')
        book.pub_date = book_dict.get('pub_date')
        book.save()

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        })

    def delete(self, request, pk):
        """
        删除图书
        路由： DELETE /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({},status=404)

        book.delete()

        return JsonResponse({},status=204)

from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView


class BooksListAPIView(APIView):
    def get(self,request):

        query_params = request.query_params
        books = BookInfo.objects.all()
        # 2.创建序列化器，并传递查询结果集（设置many=True）
        serializer = BookInfoModelSerializer(instance=books, many=True)
        # 3.返回响应 serializer.data 就是字典列表
        # return JsonResponse({'code':'get','books':serializer.data})
        from rest_framework import status
        return Response(serializer.data,status=status.HTTP_200_OK)

    def post(self,request):
        data = request.data
        serailizer = BookInfoModelSerializer(data=data)
        if serailizer.is_valid():
            serailizer.save()
            return Response(serailizer.data)
        else:
            return Response({'msg':'保存失败'})
        # return JsonResponse({'code':'post'})

##############   二级视图   列表    ######
from rest_framework.generics import GenericAPIView
from book.models import BookInfo
from book.serializers import BookInfoModelSerializer


class BookListGenericView(GenericAPIView):
    # def get_queryset(self):
    #     return BookInfo.objects.all()
    queryset = BookInfo.objects.all()

    # def get_serializer_class(self):
    #     return BookInfoModelSerializer
    serializer_class = BookInfoModelSerializer

    def get(self,request):
        books = self.get_queryset()
        serializer = self.get_serializer(books,many=True)
        return Response(serializer.data)

    def post(self,request):
        data = self.request.data
        serializer = self.get_serializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response({'msg':'保存失败'})

####     详情     ####
class BookDetialGenericView(GenericAPIView):

    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializer

    lookup_field = 'pk'
    def get(self,request,pk):
        book = self.get_object()
        serializer = self.get_serializer(book)
        return Response(serializer.data)

    def put(self,request,pk):
        book = self.get_object()
        serializer = self.get_serializer(book,data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response({'msg':'保存失败'})

    def delete(self,request,pk):
        book = self.get_object()
        book.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

#########   Mixin   #######
from rest_framework.mixins import ListModelMixin,\
CreateModelMixin,DestroyModelMixin,RetrieveModelMixin,UpdateModelMixin


class BookListGenericMixinView(ListModelMixin, CreateModelMixin, GenericAPIView):
    queryset = BookInfo.objects.all()

    serializer_class = BookInfoModelSerializer
    def get(self,request):
        return self.list(request)

    def post(self,request):
        return self.create(request)

class BookDetailGenericMixinView(DestroyModelMixin, RetrieveModelMixin, UpdateModelMixin, GenericAPIView):
    queryset = BookInfo.objects.all()

    serializer_class = BookInfoModelSerializer

    def get(self,request,pk):
        return self.retrieve(request)

    def put(self,request,pk):
        return self.update(request)

    def delete(self,request,pk):
        return self.destroy(request)

#####        视图集    ######
from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet
from rest_framework.authentication import TokenAuthentication,SessionAuthentication

#权限,认证



from rest_framework.pagination import PageNumberPagination
class PageNum(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'pg'
    max_page_size = 20

class BookInfoModelViewSet(ModelViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializer
    # authentication_classes = [TokenAuthentication]
    pagination_class = PageNum